import { addPageToBasic, addPageToIframe } from '@/router'
import { useIconRender } from '@/composables'
import { $t } from '@/locales'
import { Menu } from '@/typings/menu'

export enum OpenType {
    DEFAULT = 1,
    IFRAME = 2,
    DIALOG = 3,
    LAYER = 4,
    NEW_WINDOW = 5
}

/**
 * 将权限路由转换成菜单
 * @param menus - 路由
 */
export function transformMenu(menus: Menu[]): App.GlobalMenuOption[] {
    const globalMenu: App.GlobalMenuOption[] = []
    menus.forEach((menu) => {
        const { name, items, permissionKey, icons, url, isMenu, openType, openOption } =
            menu
        if (openOption) {
            menu.openOption = JSON.parse(openOption)
        }
        if (openType == OpenType.IFRAME) {
            //如果是iframe类型的菜单，需要转换下url
            menu.routeUrl = `/iframe/${permissionKey}`
            menu.url = `/iframe/${permissionKey}?${
                menu.openOption?.urlWithToken ? 't=' : ''
            }&url=${encodeURIComponent(url ?? '')}`
        }

        const routeName = permissionKey as string
        let menuChildren: App.GlobalMenuOption[] | undefined
        if (items && items.length > 0) {
            menuChildren = transformMenu(items)
        }
        if (isMenu && !items) {
            transformMenuToRoute(menu)
        }
        const menuItem: App.GlobalMenuOption = addPartialProps({
            menu: {
                key: routeName,
                label: name,
                routeName,
                routePath: menu.url ?? '',
                openType,
                openOption: menu.openOption
            },
            icon: icons?.startsWith('local:') ? undefined : icons,
            localIcon: icons?.startsWith('local:')
                ? icons.replace('local:', '')
                : undefined,
            children: menuChildren
        })

        globalMenu.push(menuItem)
    })

    return globalMenu
}

function transformMenuToRoute(menu: Menu) {
    const { openType } = menu
    switch (openType) {
        case OpenType.DEFAULT:
            addPageToBasic(menu)
            break
        case OpenType.IFRAME:
            addPageToIframe(menu)
            break
        default:
    }
}

/**
 * 翻译菜单
 * @param menus
 * @returns
 */
export function translateMenuLabel(
    menus: App.GlobalMenuOption[]
): App.GlobalMenuOption[] {
    const globalMenu: App.GlobalMenuOption[] = []
    menus.forEach((menu) => {
        let menuChildren: App.GlobalMenuOption[] | undefined
        if (menu.children && menu.children.length > 0) {
            menuChildren = translateMenuLabel(menu.children)
        }
        const menuItem: App.GlobalMenuOption = {
            ...menu,
            children: menuChildren,
            label: menu.i18nTitle ? $t(menu.i18nTitle) : menu.label
        }
        globalMenu.push(menuItem)
    })
    return globalMenu
}

/**
 * 获取当前路由所在菜单数据的paths
 * @param activeKey - 当前路由的key
 * @param menus - 菜单数据
 */
export function getActiveKeyPathsOfMenus(
    activeKey: string,
    menus: App.GlobalMenuOption[]
) {
    let paths: string[] = []
    for (const menu of menus) {
        paths = getActiveKeyPathsOfMenu(activeKey, menu)
        if (paths.length) {
            return paths
        }
    }
    return paths
}

function getActiveKeyPathsOfMenu(activeKey: string, menu: App.GlobalMenuOption) {
    const keys: string[] = []
    if (activeKey == menu.routeName) {
        keys.push(menu.routeName)
        return keys
    }
    if (menu.children) {
        for (const sub of menu.children) {
            keys.push(...getActiveKeyPathsOfMenu(activeKey, sub))
            if (keys.length > 0) {
                keys.unshift(menu.routeName)
                break
            }
        }
    }
    return keys
}

/** 给菜单添加可选属性 */
function addPartialProps(config: {
    menu: App.GlobalMenuOption
    icon?: string
    localIcon?: string
    children?: App.GlobalMenuOption[]
}) {
    const { iconRender } = useIconRender()

    const item = { ...config.menu }

    const { icon, localIcon, children } = config

    if (localIcon) {
        Object.assign(item, { icon: iconRender({ localIcon }) })
    }

    if (icon) {
        Object.assign(item, { icon: iconRender({ icon }) })
    }

    if (children) {
        Object.assign(item, { children })
    }
    return item
}
